package org.apache.commons.dbutils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.dbutils.AbstractRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.lang.StringUtils;


/**
 * 扩展<code>BasicRowProcessor</code>。<br>
 * 和<code>BasicRowProcessor</code>不同之处在于：
 * 记录集到Array和Map的转化中对于为null的字段转化为empty("")。
 * <p>
 * Copyright: Copyright (c) May 13, 2009 10:43:28 AM
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: chengyao
 * <p>
 * Version: 1.0
 * <p>
 * 
 * @see org.apache.commons.dbutils.BasicRowProcessor
 */
@SuppressWarnings("unchecked")
public class TrimToEmptyRowProcessor extends AbstractRowProcessor<String> {
    
    /**
     * BasicRowProcessor constructor.  Bean processing defaults to a 
     * BeanProcessor instance.
     */
    public TrimToEmptyRowProcessor() {
        super();
    }
    
    /**
     * BasicRowProcessor constructor.
     * @param convert The BeanProcessor to use when converting columns to 
     * bean properties.
     * @since DbUtils 1.1
     */
    public TrimToEmptyRowProcessor(BeanProcessor convert) {
        super(convert);
    }
    
    /**
     * Convert a <code>ResultSet</code> row into an <code>Object[]</code>.
     * This implementation copies column values into the array in the same 
     * order they're returned from the <code>ResultSet</code>.  Array elements
     * will be set to <code>null</code> if the column was SQL NULL.
     *
     * @see org.apache.commons.dbutils.RowProcessor#toArray(java.sql.ResultSet)
     */
    @Override
    public String[] toArray(ResultSet rs) throws SQLException {
        ResultSetMetaData meta = rs.getMetaData();
        int cols = meta.getColumnCount();
        String[] result = new String[cols];

        for (int i = 0; i < cols; i++) {
            result[i] = StringUtils.trimToEmpty(rs.getString(i + 1));
        }

        return result;
    }

    /**
     * Convert a <code>ResultSet</code> row into a <code>Map</code>.  
     * if value is null set the map value to empty(""), This 
     * implementation returns a <code>Map</code> with case insensitive column
     * names as keys.  Calls to <code>map.get("COL")</code> and 
     * <code>map.get("col")</code> return the same value.
     * @see org.apache.commons.dbutils.RowProcessor#toMap(java.sql.ResultSet)
     */
	@Override
    public Map<String, String> toMap(ResultSet rs) throws SQLException {
        Map<String, String> result = new CaseInsensitiveHashMap();
        ResultSetMetaData rsmd = rs.getMetaData();
        int cols = rsmd.getColumnCount();

        for (int i = 1; i <= cols; i++) {
            result.put(rsmd.getColumnName(i), StringUtils.trimToEmpty(rs.getString(i)));
        }

        return result;
    }
    
}
